package com.thread;

import java.util.ArrayList;
import java.util.List;

public class JUC_WaitNotify_good_20 {

     List<Object> list = new ArrayList<>();
    /*volatile*/
    void add(Object o){
        list.add(o);
    }
    int size(){
        return list.size();
    }

    public static void main(String[] args) {
        final Object lock = new Object();

        JUC_WaitNotify_good_20 t = new JUC_WaitNotify_good_20();

        Thread t1 = new Thread(() -> {
            synchronized (lock){
                System.out.println("t1 启动" );

                if(t.size() != 5){
                    try {
                        lock.wait();
                        System.out.println("t1 get lock");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                lock.notify();
                System.out.println("t1 end");
            }
        }, "t1");

        Thread t2 = new Thread(() -> {

            synchronized (lock){
                for(int i=0;i<10;i++){

                    t.add(new Object());
                    System.out.println("add "+i);

                    if(t.size() == 5){
                        lock.notify();//并没有释放锁 所以t2会执行完才会欢喜t1来执行

                        try {
                            lock.wait();//释放锁
                            System.out.println("t2 get lock");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }


            }
        }, "t2");

        t1.start();
        t2.start();
    }

}
